//
//  ViewController.swift
//  Auto114
//
//  Created by yb on 2020/8/24.
//  Copyright © 2020 RMCtl. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet var textView: UITextView!
    @IBOutlet var textField: UITextField!

    let targetTime = "2020-08-25 08:00"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        LogViewUtility.outputView = textView
        InputPhoneCode.shared.input = textField

    }
    
    @IBAction func autoStart() {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let date = formatter.date(from: targetTime) ?? Date()
        LogViewUtility.log("auto start at: \(date)")
        Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (t) in
            let interval = date.timeIntervalSinceNow
            if interval < 4.5 {
                LogViewUtility.log("auto start now!")
                self.start()
                t.invalidate()
            } else {
                LogViewUtility.log("auto will start after \(Int(interval))s")
            }
        }
    }
    
    @IBAction func startButtonAct() {
        start()
    }

    func start() {
        
        let targetDate = Date(timeIntervalSinceNow: 24 * 3600 * 7)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateStr = formatter.string(from: targetDate)
//        let dateStr = "2020-09-09" //test
        LogViewUtility.log("targetDate: \(dateStr)")
        
        let worker1 = Worker()
        worker1.name = "特需号"
        worker1.targetDate = dateStr
        worker1.work()
        
//        let worker2 = Worker()
//        worker2.name = "普通专家"
//        worker2.targetDate = dateStr
//        worker2.work()
    }

}


class LogViewUtility {
    static var outputView: UITextView?
    static let processQueue = DispatchQueue(label: "log.process.queue", qos: .userInteractive)
    static var contents = [String]()
    static func log(_ str: String) {
        let ts = Date().timeIntervalSince1970
        processQueue.async {
            contents.insert("\(Int(ts*1000)): \(str)", at: 0)
            if contents.count > 300 {
                contents = Array(contents[0 ..< 300])
            }
            let out = contents.joined(separator: "\n")
            DispatchQueue.main.async {
                guard let outView = outputView else {
                    return
                }
                outView.text = out
                outView.setContentOffset(CGPoint(x: 0, y: max(0, outView.contentSize.height - outView.frame.size.height)), animated: false)
            }
        }
        
    }
}
